package com.gjy.spring.aspect;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-02-17 16:58:09
 */
@EnableAsync
@Configuration
public class TaskExecutor {

    @Bean("fileAsync")
    public Executor fileAsync() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(10);
        executor.setThreadFactory(
                new ThreadFactory() {
                    private final AtomicLong index = new AtomicLong(1);

                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "FileExecutor-task-pool-thread-" + index.getAndIncrement());
                    }
                }
        );
        executor.setRejectedExecutionHandler((r, executor1) -> {
            if (!executor1.isShutdown()) {
                try {
                    executor1.getQueue().put(r);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        executor.initialize();
        return executor;
    }

}
